package com.kaibes.im.view.fragment;

import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.kaibes.im.R;
import com.kaibes.im.model.SocketWorker;
import com.kaibes.im.model.adapter.OnlineListviewAdapter;
import com.kaibes.im.model.hanlder.BaseHandler;

public class AllOnlineFragment extends KaibesFragment {

    private ListView listview;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    Bundle savedInstanceState) {
	View rootView = inflater.inflate(R.layout.fragment_all_online,
		container, false);
	setHandler(new BaseHandler<AllOnlineFragment>(this) {

	    @Override
	    public void handleMessage(Message msg) {
		reset();
	    }
	});
	listview = (ListView) rootView.findViewById(R.id.testResultListview);
	listview.setAdapter(new OnlineListviewAdapter(getKaibesActivity()));
	return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
	getView().findViewById(R.id.testBack).setOnClickListener(
		new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			onBackPressed();
		    }
		});

	listview.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> parent, View view,
		    int position, long id) {
		TextView tv = (TextView) view
			.findViewById(R.id.testContactname);
		String contactname = tv.getText().toString();

		if (contactname.equals(getKaibesApplication().getUsername())) {
		    getKaibesActivity().getToastData()
			    .setMessage("不可以添加自己为好友！");
		    getKaibesActivity().showToast();
		} else if (getKaibesApplication().getContactInformationData(
			contactname) != null) {
		    getKaibesActivity().getToastData().setMessage("对方已经是您的好友！");
		    getKaibesActivity().showToast();
		} else {
		    onBackPressed();
		    getKaibesActivity().getProgressDialogData().reset()
			    .setTitle("搜索用户").setMessage("正在搜索用户。。。");
		    getKaibesActivity().showProgressDialog();

		    getKaibesActivity().getKaibesApplication().sendData(1,
			    SocketWorker.ACTION_SEARCH, contactname, "", "",
			    "", "");
		}

	    }
	});
	super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void reset() {
	((OnlineListviewAdapter) listview.getAdapter()).notifyDataSetChanged();
    }

    @Override
    public boolean onBackPressed() {
	getKaibesActivity().changeFragment(getLastFragmentAndSetNull());
	return false;
    }

}
